const Mock = require('mockjs')
const { list: listOrgUnits, find: findOrgUnit } = require('./org-units')

const Rooms = []
const orgUnitsPage = listOrgUnits(1, 10, 1)
for (let i = 0; i < orgUnitsPage.data.records.length; ++i) {
  for (let j = 1; j <= 3; ++j) {
    Rooms.push(Mock.mock({
      id: i * 3 + j,
      orgUnitId: orgUnitsPage.data.records[i].id,
      name: j + '号房',
      balance: (j - 1) * 1000,
      luckyMoney: (j - 1) * 100
    }))
  }
}

function add(room) {
  const r = JSON.parse(JSON.stringify(room))
  r.id = Rooms[Rooms.length - 1].id + 1
  r.balance = 0
  Rooms.push(r)
}

function list(page, limit, name, orgUnitId) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  orgUnitId = orgUnitId ? parseInt(orgUnitId) : null
  let mocks = Rooms.filter(item => {
    if (orgUnitId && item.orgUnitId !== orgUnitId) return false
    return !(name && (!item.name || item.name.indexOf(name) === -1))
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1)).map(item => {
    const o = findOrgUnit(item.orgUnitId)
    if (o) {
      item.orgUnitName = o.name
    }
    return item
  })
  return { success: true, data: { total: total, records: mocks }}
}

function find(id) {
  id = id ? parseInt(id) : null
  for (let i = 0; i < Rooms.length; ++i) {
    if (Rooms[i].id === id) {
      return Rooms[i]
    }
  }
  return null
}

module.exports = { list, add, find }
